package com.example.synccenter.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * MyBatis-Plus配置类，实现自动填充功能。
 * 在插入和更新操作时，自动填充创建人、创建时间、更新人、更新时间等审计字段。
 */
@Configuration
public class MybatisPlusConfig implements MetaObjectHandler {

    /**
     * 插入操作自动填充
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        String username = getCurrentUsername();
        LocalDateTime now = LocalDateTime.now();
        
        this.strictInsertFill(metaObject, "creator", String.class, username);
        this.strictInsertFill(metaObject, "createAt", LocalDateTime.class, now);
        this.strictInsertFill(metaObject, "updator", String.class, username);
        this.strictInsertFill(metaObject, "updateAt", LocalDateTime.class, now);
    }

    /**
     * 更新操作自动填充
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        String username = getCurrentUsername();
        LocalDateTime now = LocalDateTime.now();
        
        this.strictUpdateFill(metaObject, "updator", String.class, username);
        this.strictUpdateFill(metaObject, "updateAt", LocalDateTime.class, now);
    }

    /**
     * 获取当前操作用户
     * @return 当前用户名
     */
    private String getCurrentUsername() {
        return "system";
    }
} 